<?php
/***************************************************************************
 *   copyright : (C) 2009 Udrea Cristian
 *   site : http://code.google.com/p/testauction-php
 ***************************************************************************/

/***************************************************************************
 *   This program is free software; you can redistribute it and/or modify
 *   it under the terms of the GNU Lesser General Public License as 
 *   published by the Free Software Foundation; either version 2 of the
 *   License, or (at your option) any later version. Although none of the
 *   code may be sold. If you have been sold this script, get a refund.
 ***************************************************************************/
class AuctionHandler {
	public function getUserCreditInfo($user) {
		if(eregi("^([0-9a-z])+$", $user)) {
			$resultset = execute_query('SELECT userkey FROM '.TBL_USERS.' WHERE username = ?', array($user));
			$userkey = (count($resultset) == 1) ? $resultset[0]['userkey'] : '';
			$resultset = execute_query('SELECT * FROM '.TBL_CREDIT.' WHERE userkey = ?', array($userkey));
			return $resultset[0];
		}
		return array();
	}

	public function setUserCreditInfo($array) {
		return execute_update('UPDATE ' . TBL_CREDIT . ' SET credit_balance = ?, give_bonus = ?, offers_left = ? WHERE userkey = ?',
			array($array['credit_balance'], $array['give_bonus'], $array['offers_left'], $array['userkey']));
	}

	public function getUserOffers($user) {
		if(eregi("^([0-9a-z])+$", $user)) {
			$resultset = execute_query('SELECT userkey FROM '.TBL_USERS.' WHERE username = ?', array($user));
			$userkey = (count($resultset) == 1) ? $resultset[0]['userkey'] : '';
			$resultset = execute_query('SELECT * FROM '.TBL_OFFERS.' WHERE userkey = ?', array($userkey));
			return $resultset;
		}
		return array();
	}

	public function getAuctionLatestOffer($id) {
		$result = $this->getAuctionLastOffers($id);
		return $result[0];
	}

	public function getAuctionLastOffers($id) {
		if(eregi("^([0-9])+$", $id)) {
			$auctioninfo = $this->getAuctionData($id);
			$step = $auctioninfo['offer_increment'];
			$price = $this->getAuctionOfferCount($id) * $step + $auctioninfo['base_price'];
			
			$resultset = execute_query('SELECT userkey, timestamp FROM '.TBL_OFFERS.' WHERE auction_id = ? ORDER BY timestamp DESC', array($id));
			$count = (count($resultset) < 10) ? count($resultset) : 10;
			$result = array();
			for($i = 0; $i < $count; $i++){
				$dbarray  = execute_query('SELECT username FROM '.TBL_USERS.' WHERE userkey = ?', array($resultset[$i]['userkey']));
				$result[] = array('username'=>$dbarray[0]['username'], 'date'=>date('H:i:s', $resultset[$i]['timestamp']),
					'price'=>$price - ($step * $i), 'timestamp'=>$resultset[$i]['timestamp'], 'userkey' => $resultset[$i]['userkey']);
			}
			return $result;
		}
		return array();
	}

	public function getAuctionOfferCount($id) {
		if(eregi("^([0-9])+$", $id)) {
			$resultset = execute_query('SELECT * FROM '.TBL_OFFERS.' WHERE auction_id = ?', array($id));
			return count($resultset);
		}
		return -1;
	}

	public function getProductData($id) {
		if(eregi("^([0-9])+$", $id)) {
			$resultset = execute_query('SELECT * FROM '.TBL_PRODUCTS.' WHERE product_id = ?', array($id));
			return $resultset[0];
		}
		return array();
	}

	public function getAuctionData($id) {
		if(eregi("^([0-9])+$", $id)) {
			$resultset = execute_query('SELECT * FROM '.TBL_AUCTIONS.' WHERE auction_id = ?', array($id));
			return $resultset[0];
		}
		return array();
	}

	public function getAuctionsWon($user) {
		if(eregi("^([0-9a-z])+$", $user)) {
			$resultset = execute_query('SELECT userkey FROM '.TBL_USERS.' WHERE username = ?', array($user));
			$userkey = (count($resultset) == 1) ? $resultset[0]['userkey'] : '';
			/* Lengthy query process */
			$auctions = execute_query('SELECT product_id, auction_id, base_price, offer_increment FROM '.TBL_AUCTIONS.' WHERE closed = 1');			
			$offer_array = array();
			for($i = 0; $i < count($auctions); $i++) {
				$offer_query = execute_query('SELECT * FROM '.TBL_OFFERS.' WHERE userkey = ? AND auction_id = ?', 
					array($userkey, $auctions[$i]['auction_id']));

				for($j = 0; $j < count($offer_query); $j++) {
					
					$state_text = "<button class=\"green-button\" onclick=\"acceptAuction(".$auctions[$i]['auction_id'].")\" style=\"margin-top: 10px\">Accepta</button>"
						."<button class=\"red-button\" onclick=\"refuseAuction(".$auctions[$i]['auction_id'].")\" style=\"margin-top: 10px\">Refuza</button>";
					$temp_r = execute_query('SELECT od_claim_type, od_claimed, od_status FROM '. TBL_ORDERS 
						.' WHERE auction_id = ? AND od_shipping_userkey = ?', array($auctions[$i]['auction_id'], $userkey));
					$n_items = count($temp_r);
					if($n_items == 1) {
						$temp_r = $temp_r[0];
						if($temp_r['od_claimed'] == "Y") {
							$state_text = "";
							if($temp_r['od_claim_type'] == "Accepted") {
								$state_text .= "<img style=\"border: 0;\" alt=\"Acceptat\" title=\"Acceptat\" src=\"images/status/accepted.png\"/>";
								switch($temp_r['od_status']) {
								case "New" :
									$state_text .= "<img style=\"border: 0;\" alt=\"Neplatit\" title=\"Neplatit\" src=\"images/status/new.png\"/><br />";
									$state_text .= "<button class=\"orange-button\" onclick=\"payAuction(".$auctions[$i]['auction_id'].")\" style=\"margin-top: 10px\">Plateste</button>";
									break;
								case "Paid" :
									$state_text .= "<img style=\"border: 0;\" alt=\"Platit\" title=\"Platit\" src=\"images/status/paid.png\"/>";
									break;
								case "Shipped" :
									$state_text .= "<img style=\"border: 0;\" alt=\"Trimis\" title=\"Trimis\" src=\"images/status/shipped.png\"/>";
									break;
								case "Completed" :
									$state_text .= "<img style=\"border: 0;\" alt=\"Complet\" title=\"Complet\" src=\"images/status/complete.gif\"/>";
									break;
								case "Cancelled" :
									$state_text .= "<img style=\"border: 0;\" alt=\"Anulat\" title=\"Anulat\" src=\"images/status/cancel.png\"/>";
									break;
							}
							}
							else {
								$state_text .= "<img style=\"border: 0;\" alt=\"Refuzat\" title=\"Refuzat\" src=\"images/status/refused.png\"/>";
							}
						}
					}
					$offer_array[] = array('product_id' => $auctions[$i]['product_id'], 
						'auction_id' => $auctions[$i]['auction_id'],
						'base_price' => $auctions[$i]['base_price'],
						'offer_increment' => $auctions[$i]['offer_increment'],
						'timestamp' => $offer_query[$j]['timestamp'],
						'state' => $state_text);
				}
			}
			return $offer_array;
		}
		return array();
	}

	public function getLastClosedAuctions() {
		return execute_query('SELECT auction_id, product_id, offer_increment, base_price FROM ' . TBL_AUCTIONS . ' WHERE closed = 1 ORDER BY closed_timestamp DESC LIMIT 10');
	}
	
	public function getOpenAuctions() {
		return execute_query('SELECT * FROM ' . TBL_AUCTIONS . ' WHERE closed = 0 ORDER BY starts_timestamp ASC');
	}
	
	public function getOpenAuctionsStartDates() {
		return execute_query('SELECT starts_timestamp FROM ' . TBL_AUCTIONS . ' WHERE closed = 0 ORDER BY starts_timestamp DESC');
	}
	
	public function addAuctionOffer($userkey, $id) {
		return execute_update('INSERT INTO ' . TBL_OFFERS . ' (auction_id, userkey, timestamp) VALUES (?, ?, ?)',
			array($id, $userkey, time()));
	}
	
	public function existsAuctionOrder($id, $userkey) {
		$resultset = execute_query ('SELECT od_id FROM ' . TBL_ORDERS . ' WHERE auction_id = ? AND od_shipping_userkey = ?',
			array($id, $userkey));
		if(count($resultset) == 1) {
			return TRUE;
		}
		return FALSE;
	}
	public function acceptAuctionOrder($id, $userkey) {
		$auctioninfo = $this->getAuctionData($id);
		$price = $this->getAuctionOfferCount($id) * $auctioninfo['offer_increment'] + $auctioninfo['base_price'];
		execute_update('UPDATE ' . TBL_ORDERS . ' SET od_claim_type=\'Accepted\', od_claimed = \'Y\', od_last_update = NOW(), od_price = ? WHERE auction_id = ? AND od_shipping_userkey = ?', 
			array($price, $id, $userkey));
	}
	public function refuseAuctionOrder($id, $userkey) {
		execute_update('UPDATE ' . TBL_ORDERS . ' SET od_claim_type=\'Refused\', od_claimed = \'Y\', od_last_update = NOW(), od_status = \'Cancelled\' WHERE auction_id = ? AND od_shipping_userkey = ?', 
			array($id, $userkey));
	}
	public function payAuctionOrder($id, $userkey) {
		// TODO : Nothing here yet
	}
}
$auctionDB = new AuctionHandler();
?>
